package com.liveinstars.common.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by guoyanjiang on 2018-12-02.
 */
public class ConvertUtil {

    /**
     * 转换List
     * @param sourceList
     * @param c
     * @param <T>
     * @return
     */
    public static <T> List<T> convertList(List sourceList, Class<T> c){
        List<T> targets = new ArrayList<>(sourceList.size());
        sourceList.forEach(source -> targets.add(convert(source, c)));
        return targets;
    }

    /**
     * 转换Bean
     * @param source
     * @param c 目标类必须有空的构造方法
     * @param <T>
     * @return
     */
    public static <T> T convert(Object source, Class<T> c) {
        try {
            T target = c.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
